package org.smart4j.framework.helper;

import org.apache.commons.lang3.ArrayUtils;
import org.smart4j.framework.annotation.Injection;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 *
 * 依赖注入助手类
 *
 * @author: Mr.Zhou
 * @create: 2018-10-24 14:50
 **/
public final class IocHelper {

    static {
        Map<Class<?>,Object> beanMap=BeanHelper.getBeanMap();
        if(beanMap.size()>0){
            for (Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()){
                Class<?> beanClass=beanEntry.getKey();
                Object beanInstance=beanEntry.getValue();
                Field[] beanFields=beanClass.getDeclaredFields();
                if(ArrayUtils.isNotEmpty(beanFields)){
                    for (Field beanField:beanFields){
                        if(beanField.isAnnotationPresent(Injection.class)){
                            Class<?> beanFieldClass=beanField.getType();
                            Object beanFieldInstance=beanMap.get(beanFieldClass);
                            if(beanFieldInstance!=null){
                                ReflectionUtil.setField(beanInstance.getClass(),beanField,beanFieldInstance);
                            }
                        }
                    }
                }
            }

        }
    }

}
